package com.shouhuobao.bhi.collectpoint;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ZoomControls;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.collectplus.express.BaseActivity2;
import com.collectplus.express.R;
import com.collectplus.express.app.Intents;
import com.collectplus.express.logic.AppHttp;
import com.collectplus.express.logic.AppLogic;
import com.collectplus.express.logic.AppResult;
import com.collectplus.express.logic.DialogMgr;
import com.collectplus.express.logic.JSON;
import com.collectplus.express.logic.MsgID;
import com.collectplus.express.model.ServicePointBean;
import com.collectplus.express.tools.CollectPointUtils;
import com.collectplus.express.view.CircleImageView;

import droid.frame.umeng.UMeng;
import droid.frame.utils.lang.Str;

/**
 * 网点详情
 *
 * @author coffee <br>
 *         2016-10-18上午11:00:34
 */
public class ServicePointDetailsActivity extends BaseActivity2 implements OnClickListener {

    private MapView mMapView;
    private BaiduMap mBaiduMap;

    // 详情界面
    private ImageView mLogo;// 网点logo或者柜子logo
    private TextView mName;// 网点名称
    private ImageView mFavotite;// 收藏
    private TextView mAddress;// 网点地址
    private TextView mAddressCopy;// 拷贝地址
    private TextView mPhone;// 联系方式
    private TextView mPhoneCall;// 拨打电话
    private TextView mServiceTime;// 服务时间
    private TextView mServiceType;// 服务类型
    private Button mGoThereLayout;
    private CircleImageView mLogoImage;  //网点logo圆形图
    private ServicePointBean item;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        String stationId = getIntent().getStringExtra("stationId");
        int type = getIntent().getIntExtra("type", 2);
        item = (ServicePointBean) getIntent().getSerializableExtra("item");
        super.onCreate(savedInstanceState);
        // 查询详情
        if (item == null) {
            AppHttp.getInstance().servicePointDetails(stationId, type);
        } else {
            AppHttp.getInstance().servicePointDetails(item.getId(), item.getType());
        }
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.service_point_details);
        super.findViewById();
        // AppHttp.getInstance().cancelStoreUpPoints(mShbUserId, mPointId);
        mLogo = (ImageView) findViewById(R.id.service_point_logo_icon);
        mLogoImage = (CircleImageView) findViewById(R.id.service_point_logo);
        mName = (TextView) findViewById(R.id.service_point_name);
        mFavotite = (ImageView) findViewById(R.id.service_point_favorite);
        mAddress = (TextView) findViewById(R.id.service_point_address);
        mAddressCopy = (TextView) findViewById(R.id.service_point_address_copy);
        mPhone = (TextView) findViewById(R.id.service_point_phone);
        mPhoneCall = (TextView) findViewById(R.id.service_point_call);
        mServiceTime = (TextView) findViewById(R.id.service_point_time);
        mServiceType = (TextView) findViewById(R.id.service_point_type);
        mGoThereLayout = (Button) findViewById(R.id.collect_agent_to_pay);

        mFavotite.setVisibility(View.INVISIBLE);// 详情获取回来之前 不显示、从而不能触发单击事件
        mFavotite.setOnClickListener(this);
        initMapView();
        if (item != null) {
            updateData();
        }
    }

    private void initMapView() {
        // 地图初始化
        mMapView = (MapView) findViewById(R.id.bmapView);
        int count = mMapView.getChildCount();
        for (int i = 0; i < count; i++) {
            View child = mMapView.getChildAt(i);
            // 隐藏缩放按键 ZoomControl
            if (child instanceof ImageView || child instanceof ZoomControls) {
                child.setVisibility(View.INVISIBLE);
            }
        }
        mBaiduMap = mMapView.getMap();
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
    }

    /**
     * 更新网点数据
     */
    private void updateData() {
        if (item.isStation()) {
            if (Str.isEmpty(item.getHeadImage())) {
                mLogo.setVisibility(View.VISIBLE);
                mLogoImage.setVisibility(View.GONE);
                mLogo.setImageResource(R.drawable.service_point_logo2);
            } else {
                mLogo.setVisibility(View.GONE);
                mLogoImage.setVisibility(View.VISIBLE);
                AppLogic.getInstance().loadImage(item.getHeadImage(), mLogoImage);
                mLogoImage.setOnClickListener(this);
            }
        } else {// 速递易
            mLogo.setVisibility(View.VISIBLE);
            mLogoImage.setVisibility(View.GONE);
            mLogo.setImageResource(R.drawable.service_point_logo1);
        }
        getAppTitle().setCommonTitle(item.getName());
        mName.setText(item.getName());
        // 经纬度不为空
        if (item.getLatitude() != null && item.getLongitude() != null) {
            mMapView.getMap().clear();
            addMarkToMap(Double.parseDouble(item.getLatitude()), Double.parseDouble(item.getLongitude()));
        }
        mAddress.setText(item.getAddress());
        mAddressCopy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showToast("复制地址成功");
                // 复制地址
                CollectPointUtils.copyTest(getContext(), mAddress.getText().toString());
            }
        });
        // 柜子 -- 没有电话
        if (isEmpty(item.getPhone())) {
            ((ViewGroup) mPhone.getParent()).setVisibility(View.GONE);
        } else {
            ((ViewGroup) mPhone.getParent()).setVisibility(View.VISIBLE);
            mPhone.setText(item.getPhone());
            mPhoneCall.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intents.dialOrCall(mPhone.getText().toString());
                }
            });
        }
        mServiceTime.setText(item.getServiceTime());
        mServiceType.setText(item.getPostCooperationTypeName());
        mGoThereLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // goThere(item.getPostStationBDLatitude(), item.getPostStationBDLongitude());
                UMeng.click(getContext(), "servicePoint_goto_map_click");
                Intents.navigation(item.getLatitude(), item.getLongitude(), //
                        item.getGdlatitude(), item.getGdLongitude(), item.getAddress());
            }
        });
    }

    /**
     * 更新网点的收藏状态
     */
    private void updateFavorite() {
        mFavotite.setVisibility(View.VISIBLE);
        // 是否已收藏
        if (item.isFavorite()) {
            mFavotite.setImageResource(R.drawable.service_point_favorite);
        } else {
            mFavotite.setImageResource(R.drawable.service_point_favorite2);
        }
    }

    public boolean handleMessage(final Message msg) {
        switch (msg.what) {
            // 按照id查询网点详情
            case MsgID.service_point_details_byId:
                final AppResult<ServicePointBean> result = JSON.parser(msg.obj, ServicePointBean.class);
                // 获取常用的网点
                getContext().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (result.isSuccess()) {
                            item = result.getResult();
                            if (item != null) {
                                updateData();
                                updateFavorite();
                            }
                        } else {
                            showToast(result.getMessage());
                        }
                    }
                });
                return true;
            // 收藏
            case MsgID.service_point_favorite_yes:
                AppResult<Integer> result1 = JSON.parser(msg.obj, Integer.class);
                if (result1.isSuccess()) {
                    showToast("收藏成功");
                    item.setIsFavor(1);
                    // item.setEnshrineId(result1.getResult());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            updateFavorite();
                        }
                    });
                } else {
                    showToast(result1.getMessage());
                }
                return false;
            // 取消-收藏
            case MsgID.service_point_favorite_no:
                AppResult<?> result2 = JSON.parser(msg.obj);
                if (result2.isSuccess()) {
                    showToast("取消收藏成功");
                    item.setIsFavor(0);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            updateFavorite();
                        }
                    });
                } else {
                    showToast(result2.getMessage());
                }
                return false;
            default:
                return super.handleMessage(msg);
        }
    }

    private void addMarkToMap(double la, double lo) {
        LatLng llB = new LatLng(la, lo);
        BitmapDescriptor bdB = BitmapDescriptorFactory.fromResource(R.drawable.collect_point_store_selected);
        OverlayOptions ooB = new MarkerOptions().position(llB).icon(bdB).zIndex(9).draggable(true);
        mMapView.getMap().addOverlay(ooB);
        int zoomLevel = 15;// 缩放级别14-1公里, 15-500米
        MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(llB, zoomLevel);
        mMapView.getMap().animateMapStatus(u);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onDestroy() {
        if (mMapView != null) {
            mMapView.onDestroy();
            mMapView = null;
        }
        super.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100 && RESULT_OK == resultCode) {
            setResult(RESULT_OK, data);
            finish();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.service_point_favorite:
                // 当前已经收藏
                AppHttp.getInstance().servicePointFavorite(item.getIsFavor() == 0 ? 1 : 0, item.getId(), item.getCode());
                break;
            case R.id.service_point_logo:
                DialogMgr.showLargeStationPhoto(getContext(), item.getHeadImage());
                break;
        }
    }
}
